/*
 * - xtabs contains several buttons/anchors/etc that can toggle div block that 
 *   has the similar id. One div is showing, the others are hiden. 
 */

(function( $ ){
	
	$.xurls = function(options) {
		var settings = $.extend({}, $.xurls.defaults, options);
		
		if(settings.operation == "set") {
			//jQuery.debug("set");
			return setSeg(settings.url, settings.key, settings.value);
		} else if(settings.operation == "get") {
			//jQuery.debug("get");
			return getSeg(settings.url, settings.key);
		} else if(settings.operation == "key") {
			//jQuery.debug("key");
			return changeKey(settings.url, settings.okey, settings.akey);
		} else {
			return "";
		}	
	};
	
	function findSegBegin(url, key) {
		var index = url.indexOf("/" + key + "/");
		if(index < 0) {
			return -1;
		} else {
			return index + key.length + 2;
		}
	}
	
	function findSegEnd(url, beginIndex) {
		if(beginIndex < 0) {
			return -1;
		} else {
			var index = url.substring(beginIndex).indexOf("/");
			if(index < 0) {
				return -1;
			} else {
				return beginIndex + index;
			}
		}
	}
	
	function changeKey(url, okey, akey) {
		var bi = url.indexOf("/" + okey + "/") + 1;
		var ei = bi + okey.length;
		if(bi < 0) {
			return url;
		} else {
			var res = url.substring(0, bi) + akey + url.substring(ei);
			return res;
		}
	}
	
	function setSeg(url, key, value) {
		var bi = findSegBegin(url, key);
		var ei = findSegEnd(url, bi);
		if(bi < 0) {
			if(url.substring(url.length-1) != "/") {
				url += "/";
			} 
			return url + key + "/" + value + "/";
		} else if(ei < 0) {
			return url.substring(0, bi) + value;
		} else {
			return url.substring(0, bi) + value + url.substring(ei);
		}
	}
	
	function getSeg(url, key) {
		var bi = findSegBegin(url, key);
		var ei = findSegEnd(url, bi);
		//jQuery.debug("bi is " + bi + ", ei is " + ei);
		if(bi < 0) {
			return "";
		} else if(ei < 0) {
			return url.substring(bi);
		} else {
			return url.substring(bi, ei) ;
		}
	}
	
	$.xurls.defaults = {
		operation: "set", 
		url: "newcomer.com", 
		key: "key", 
		value: "value"
	};
	
})( jQuery );